

#include<avr/io.h>
#include<util/delay.h>
#include<avr/interrupt.h>
#include"DJAngles.h"

#define F_CPU 16000000UL
#define	DJNum 16
#define DEBUG 1




void portInit(void)
{
 	PORTA = 0x00;
 	DDRA  = 0xFF;
 	PORTB = 0x01;
 	DDRB  = 0x03;
 	PORTC = 0x00;
 	DDRC  = 0xFF;
 	PORTD = 0x00;
 	DDRD  = 0x00;
}

//TIMER1 initialize - prescale:64
// WGM: 0) Normal, TOP=0xFFFF
// desired value: 250KHz
// actual value: 250.000KHz (0.0%)
void timer1Init(void)
{
 	TCCR1B = 0x00; //stop

 	//TCNT1H = 0xFF; //setup
 	//TCNT1L = 0xFF;
 	TCNT1   =   0xFFFF-7500;
 	//OCR1AH = 0xFF;
 	//OCR1AL = 0xF0;
 	OCR1A=0xFFFF-2500;
 	//OCR1BH = 0xFF;
 	//OCR1BL = 0x00;
 	OCR1B=0xFFFF-5000;
 	TCCR1A = 0x00;

 	TCCR1B = 0x03; //start Timer
}

#ifdef DEBUG
void programIndicator()
{
	PORTB |=1<<1;
	_delay_ms(1000);
	PORTB &=~(1<<1);
	_delay_ms(1000);
}
#endif


ISR(TIMER1_COMPA_vect)
{
 //compare occured TCNT1=OCR1A
	PORTA=0x00;
}

ISR(TIMER1_COMPB_vect)
{
 //compare occured TCNT1=OCR1B
	PORTC=0x00;
}

ISR(TIMER1_OVF_vect)
{
	//TIMER1 has overflowed
	//TCNT1H 	=	0xFE; //reload counter high value
	//TCNT1L 	= 	0x0F; //reload counter low value
	TCNT1   =   0xFFFF-7500;
	OCR1A=0xFFFF-2500;
	OCR1B=0xFFFF-5000;

	PORTA	=	0xFF;
	PORTC	=	0xFF;
}

ISR(INT0_vect)
{
 //external interupt on INT0
}

ISR(INT1_vect)
{
 //external interupt on INT1
}

//call this routine to initialize all peripherals
void initDevices(void)
{
	//stop errant interrupts until set up
 	cli(); //disable all interrupts
 	portInit();
 	timer1Init();

 	MCUCR = 0x00;
 	GICR  = 0xC0;
 	TIMSK = 0x1C; //timer interrupt sources
 	sei(); //re-enable interrupts
 	//all peripherals are now initialized
}

int main()
{
	programIndicator();
	initDevices();
	while(1)
		programIndicator();
	return 0;
}
